package com.menu.Listener;

import com.menu.Mapper.GoodsMapper;
import com.menu.Mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 监听订单过期
 */
@Component
@Slf4j
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private GoodsMapper goodsMapper;
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        //将要失效的订单号
        String key = message.toString();
        if (key != null && key.substring(0,7).equals("OrderNo")){
            String orederId = key.substring(7);
            log.info("{}订单超时已取消",orederId);
            Long OrderId = null;
            try {
               OrderId = Long.parseLong(orederId);
            }catch (Exception e) {
                log.info("订单号转换出现异常！");
                return;
            }
            orderMapper.setOrderState(OrderId,2);
            int i = goodsMapper.recoverGoodsNUmber(OrderId);
            while (i == 0){
                i = goodsMapper.recoverGoodsNUmber(OrderId);
            }
        }
    }
}
